package com.zcf.dao;

import com.zcf.entity.UserEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.transaction.Transactional;
import java.util.List;

@Repository
public class UserDao {
    @Autowired
    private EntityManager entityManager;
    //新增、修改
    @Transactional
    public void save(UserEntity userEntity){
        entityManager.merge(userEntity);
    }
    //删除
    @Transactional
    public void del(Long id){
        UserEntity userEntity = getById(id);
        entityManager.remove(userEntity);
    }
    //按Id查询
    public UserEntity getById(Long id){
        UserEntity userEntity = entityManager.find(UserEntity.class, id);
        return userEntity;
    }
    //查询所有
    public List<UserEntity> findAll(){
        Query from_userEntity_u = entityManager.createQuery("from UserEntity u");
        return from_userEntity_u.getResultList();
    }
    //按username查询
    public List<UserEntity> findByUsername(String username){
        Query from_userEntity_u = entityManager.createQuery("from UserEntity u where u.username like :username");
        //拼接%，实现模糊查询
        String likeStr = "%".concat(username).concat("%");
        from_userEntity_u.setParameter("username",username);
        return from_userEntity_u.getResultList();
    }
}
